import axios from 'axios'
// 导入弹窗信息和样式
import { ElMessage } from 'element-plus'
import 'element-plus/theme-chalk/el-message.css'
// 导入user方法pinia
import { useUserStore } from '@/stores/user'

// 创建axios实例
const httpInstance = axios.create({
  baseURL: 'https://5987g53p36.zicp.fun',
  timeout: 5000
})

// axios请求拦截器
httpInstance.interceptors.request.use(
  (config) => {
    // 1.从pinia获取token数据
    const userStore = useUserStore()
    const token = userStore.userInfo.dataOne
    // 2.按照后端的需求拼接token数据
    if (token) {
      config.headers.Authorization = `${token}`
    }
    return config
  },
  (e) => Promise.reject(e)
)

// axios响应式拦截器
httpInstance.interceptors.response.use(
  (res) => res.data,
  (e) => {
    // 统一错误提示
    ElMessage({
      type: 'warning',
      message: '获取数据失败'
    })
    return Promise.reject(e)
  }
)

export default httpInstance
